<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive } from 'vue'
import PlanGroupApi from '@/api/linePatrol/PlanGroupApi'
import OneTimePlan from './OneTimePlan.vue'
import CyclePlan from './CyclePlan.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { usePatrolGroupStore } from '@/store/modules/PlanGroupStore'
import { BaseButton } from '@/components/Button'
import { ElMessage } from 'element-plus'
import { ElTabs, ElTabPane } from 'element-plus'
import { SendTasklistType } from '@/api/linePatrol/type'
import { useRoute } from 'vue-router'
import SetSecurCheckApi from '@/api/securcheck/SetSecurCheck'
const route = useRoute()
const GroupStore = usePatrolGroupStore()
const planType = route.meta.customParams as any
const apiStrategies = {
  LssuePlan: {
    list: PlanGroupApi.SendTasklist,
    delete: PlanGroupApi.DeletSendTask,
    add: PlanGroupApi.AddSendTaskData,
    edit: PlanGroupApi.EditSendTaskData,
    editState: PlanGroupApi.EditSendTaskState,
    SetTaskID: GroupStore.SetLssuePlanID
  },
  IssueUser: {
    list: SetSecurCheckApi.GetSecurPlanList,
    delete: SetSecurCheckApi.DeletSecurTask,
    add: SetSecurCheckApi.AddSecurTaskData,
    edit: SetSecurCheckApi.EditSecurTaskData,
    editState: SetSecurCheckApi.EditSecurTaskState,
    SetTaskID: GroupStore.SetIssueUserID
  },
  IssueCustomerUnit: {
    list: SetSecurCheckApi.GetSecurPlanList,
    delete: SetSecurCheckApi.DeletSecurTask,
    add: SetSecurCheckApi.AddSecurTaskData,
    edit: SetSecurCheckApi.EditSecurTaskData,
    editState: SetSecurCheckApi.EditSecurTaskState,
    SetTaskID: GroupStore.SetIssueCustomerUnitID
  }
}
const currentStrategy = apiStrategies[planType.planType]
const ids = ref<string[]>([])
GroupStore.setFacTaskList(planType.groupUserCom) //获取任务组名称列表
if (GroupStore.getFacTaskListAll.length == 0) {
  GroupStore.setUserListAll()
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await currentStrategy.list({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      groupUserCom: planType.groupUserCom,
      ...unref(searchParams)
    })
    currentStrategy.SetTaskID(res.rows[0])
    return {
      list: res.rows,
      total: res.total
    }
  },
  fetchDelApi: async () => {
    const res = await currentStrategy.delete(unref(ids)[0])
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'endDate',
    label: t('任务期限'),
    width: 140,
    search: {
      hidden: true
    },
    form: {
      hidden: false,
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'planName',
    label: t('计划名称'),
    width: 150,
    search: {
      hidden: false,
      component: 'Input',
      componentProps: {
        placeholder: '计划名称'
      }
    },
    table: {
      // hidden: true,
    }
  },
  {
    field: 'taskNature',
    label: t('任务类型'),
    search: {
      hidden: false,
      component: 'Input',
      componentProps: {
        placeholder: '任务类型'
      }
    }
  },
  {
    field: 'executeUser',
    label: t('计划执行人'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'stateSum',
    label: t('任务总量'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'stateTodo',
    label: t('待完成'),
    search: {
      hidden: true
    },
    table: {
      show: false
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'stateSuc',
    label: t('已完成'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'stateOutno',
    label: t('未完成'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'createBy',
    label: t('创建人'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'createTime',
    label: t('创建时间'),
    width: 140,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },

  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 150,
    fixed: 'right',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <span class="TableBtn color-[#409eff]" onClick={() => action(data.row, 'detail')}>
                {t('查看')}
              </span>
              <span
                class={data.row.status == '0' ? 'CloseBtn' : 'TableBtn'}
                onClick={() => action(data.row, data.row.status == '0' ? 'Disable' : 'edit')}
              >
                {t('修改')}
              </span>
              <span
                onClick={() => SetState(data.row.uuid, data.row.status == '0' ? 1 : 0)}
                class={data.row.status == '0' ? 'CloseBtn' : 'OpenBtn'}
              >
                {data.row.status == '0' ? '关闭' : '启用'}
              </span>
              <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                {t('删除')}
              </span>
            </>
          )
        }
      }
    }
  }
])
const saveLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加')
const OneTimeTypeRefs = ref() //一次性计划
const CyclePlanTypeRefs = ref() //周期性计划
const actionType = ref('')
//修改提交
const save = async () => {
  let write: { submit: () => any }
  if (GroupStore.activeName == '0') {
    write = unref(OneTimeTypeRefs)
  } else {
    write = unref(CyclePlanTypeRefs)
  }
  const formData = await write?.submit()
  if (formData) {
    formData['groupUserCom'] = planType.groupUserCom
    saveLoading.value = true
    saveLoading.value = false
    const res: any = ref(false)
    // 新增
    if (actionType.value == 'add') {
      res.value = await currentStrategy
        .add(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      //修改
      res.value = await currentStrategy
        .edit(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
//表格操作
const DisabledForm = ref(false)
const action = async (row: SendTasklistType, type: string) => {
  actionType.value = type
  GroupStore.ScheduleSendTaskDetail = {} //页面为空
  DisabledForm.value = false
  if (type == 'edit') {
    dialogTitle.value = '修改'
    GroupStore.setScheduleSendTaskDetail(row.uuid, planType.groupUserCom) //获取现在任务组详细信息
    dialogVisible.value = true //打开弹窗
  } else if (type == 'detail') {
    dialogTitle.value = '详情'
    DisabledForm.value = true //禁用表单
    GroupStore.setScheduleSendTaskDetail(row.uuid, planType.groupUserCom) //获取现在任务组详细信息
    dialogVisible.value = true //打开弹窗
  } else if (type == 'Disable') {
    ElMessage({
      message: '启用状态不能修改',
      type: 'error'
    })
  } else {
    GroupStore.activeName = '0' //标签页面恢复
    dialogTitle.value = '添加'
    dialogVisible.value = true //打开弹窗
  }
}
//修改状态
const SetState = async (uuid: string, status: number) => {
  const i = await currentStrategy.editState({ uuid: uuid, status: status })
  if (i) {
    getList()
    ElMessage({
      message: status == 0 ? '启用成功' : '关闭成功',
      type: 'success'
    })
  }
}
// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const delLoading = ref(false)
//删除
const delData = async (row: SendTasklistType | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.uuid]
    : elTableExpose?.getSelectionRows().map((v: SendTasklistType) => v.uuid) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
//高亮选中
const handleCurrentChange = async (currentRow: SendTasklistType) => {
  currentStrategy.SetTaskID(currentRow)
}
</script>

<template>
  <ContentWrap style="position: relative" :title="t('计划列表')">
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <BaseButton type="primary" size="small" @click="action({}, 'add')" class="AddbtnStyle">
      <Icon icon="ep:plus" :size="12" />新增
    </BaseButton>
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :highlight-current-row="true"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
      @current-change="handleCurrentChange"
    />
    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <ElTabs v-model="GroupStore.activeName" class="demo-tabs" type="border-card">
        <ElTabPane label="一次性计划" name="0">
          <OneTimePlan
            ref="OneTimeTypeRefs"
            :current-row="GroupStore.ScheduleSendTaskDetail"
            :DisabledForm="DisabledForm"
          />
        </ElTabPane>
        <ElTabPane label="周期计划" name="1">
          <CyclePlan
            ref="CyclePlanTypeRefs"
            :current-row="GroupStore.ScheduleSendTaskDetail"
            :DisabledForm="DisabledForm"
          />
        </ElTabPane>
      </ElTabs>
      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          {{ t('提交') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('关闭') }}</BaseButton>
      </template>
    </Dialog>
  </ContentWrap>
</template>
<style scoped>
/* .TableBtn {
  cursor: pointer;
  font-weight: 600;
  margin: 0 3px !important;
  color: #409eff;
} */
:deep(.el-dialog) {
  width: 700px !important;
}
:deep(.CloseBtn) {
  cursor: pointer;
  font-weight: 600;
  margin: 0 3px;
  color: darkgrey;
}
:deep(.OpenBtn) {
  cursor: pointer;
  font-weight: 600;
  margin: 0 3px;
  color: #67c23a;
}
.AddbtnStyle {
  margin-bottom: 16px;
  margin-right: 10px;
}
</style>
